from .png_info_helper import deserialize_from_filename, InfoFormat
import os
import json
import html

def sort_files_by_time(file_path_list):
    
    file_list = []
    for file_path in file_path_list:
        file_tuple = (file_path["mtime"], file_path)
        file_list.append(file_tuple)

    # 按照修改时间排序文件列表
    sorted_file_list = sorted(file_list, reverse=True)
    sorted_file_path_list = [file_tuple[1] for file_tuple in sorted_file_list]

    return sorted_file_path_list


def search_images_in_dir(dir_path, output=None):
    image_extensions = ['.jpg', '.jpeg', '.png']
    image_infos = []
    file_path_list = []
    for root, dirs, files in os.walk(dir_path):
        for file in files:
            if any(file.lower().endswith(ext) for ext in image_extensions) and "-checkpoint." not in file.lower():
                image_path = os.path.join(root, file)
                try:
                    info = deserialize_from_filename(image_path)[0]
                    info["path"] = image_path
                 
                    file_stat = os.stat(image_path)
                    info["mtime"] = file_stat.st_mtime
                    
                    image_infos.append(info)
                    
                except:
                    continue

    # 按照修改时间降序排序文件列表
    sorted_file_path_list = sort_files_by_time(image_infos)

    if output:
        with open(output, "w", encoding="utf-8") as f:
            json.dump(image_infos, f, ensure_ascii=False)

    return sorted_file_path_list

def getImageInfoHtml(info):

    imageInfo=f"""
        
        <tr>
        <td>
        <div class="image-container">
            <img src="{info.get('path','')}" alt="Image">
        </div>
        </td>
        <td>
        <div class="table-container">
            <table>
                <thead>
                    <tr>
                        <th>Parameter</th>
                        <th class="table-value">Value</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>Prompt</td>
                        <td class="table-value">{html.escape(str(info.get('prompt','')))}</td>
                    </tr>
                    <tr>
                        <td>Negative Prompt</td>
                        <td class="table-value">{html.escape(str(info.get('negative_prompt','')))}</td>
                    </tr>
                    <tr>
                        <td>Num Inference Steps</td>
                        <td class="table-value">{info.get('num_inference_steps','')}</td>
                    </tr>
                    <tr>
                        <td>Sampler</td>
                        <td class="table-value">{html.escape(str(info.get('sampler','')))}</td>
                    </tr>
                    <tr>
                        <td>Guidance Scale</td>
                        <td class="table-value">{info.get('guidance_scale','')}</td>
                    </tr>
                    <tr>
                        <td>Seed</td>
                        <td class="table-value">{info.get('seed','')}</td>
                    </tr>
                    <tr>
                        <td>Width x Height</td>
                        <td class="table-value">{info.get('width','')} x {info.get('height','')}</td>
                    </tr>
                    <tr>
                        <td>Model Name</td>
                        <td class="table-value">{html.escape(str(info.get('model_name','')))}</td>
                    </tr>
                </tbody>
            </table>
        </div>
        </td>
        </tr>
     
    """
    return imageInfo

def generateLibrary(images,output="Library.html"):
    imageInfos=""
    for image in images:
        imageInfos=imageInfos+getImageInfoHtml(image)

    html=f"""
    <!DOCTYPE html>
    <html>
    <head>
        <title>Image and Table</title>
        <style>
            body {{
                margin: 0;
                padding: 0;
                display: flex;
                flex-wrap: wrap;
                background-color: #3c3c3c;
                color: #cdcdcd;
            }}
            .image-container {{
                flex: 1 0 50%;
                max-height: 100vh;
                max-width: 50vw;
                margin: 0;
                padding: 0;
                display: flex;
                align-items: center;
                justify-content: center;
            }}
            .image-container img {{
                max-height: 100vh;
           
                object-fit: contain;
                object-position: center;
            }}
            .table-container {{
                flex: 1 0 50%;
                padding: 0 20px;
                display: flex;
                flex-direction: column;
                align-items: flex-start;
                justify-content: center;
            }}
            table {{
                border-collapse: collapse;
                width: 100%;
            }}
            th, td {{
                padding: 10px;
                text-align: left;
                border: 0px solid #ddd;
            }}
            .table-container th , .table-container td  {{
                padding: 10px;
                text-align: left;
                border: 1px solid #ddd;
            }}
            .table-value {{
                display :block;
                max-width: 300px;
                max-height: 150px;
                overflow: auto;
                border: 1px solid #ddd;
            }}

            
        </style>
    </head>
    <body>
    <table>
        <tbody>
    {imageInfos}
       </tbody>
        </table>
    </body>
    </html>

    """

    with open(output, "w", encoding="utf-8") as f:
        f.write(html)